<template>
  <el-dialog
    v-model="visible"
    title="插入签名"
    width="500px"
    :before-close="handleClose"
    class="signature-dialog">
    <div class="signature-container">
      <!-- 工具栏 -->
      <div class="signature-toolbar flex items-center gap-2 mb-4 p-2 bg-gray-50 rounded">
        <el-tooltip content="撤销" placement="bottom">
          <el-button
            size="small"
            :icon="RefreshLeft"
            @click="handleUndo"
            :disabled="!canUndo">
          </el-button>
        </el-tooltip>
        
        <el-tooltip content="清空" placement="bottom">
          <el-button
            size="small"
            :icon="Delete"
            @click="handleClear">
            清空
          </el-button>
        </el-tooltip>
        
        <el-divider direction="vertical" />
        
        <span class="text-sm text-gray-600 text-nowrap">笔刷大小：</span>
        <el-slider
          v-model="brushSize"
          :min="1"
          :max="10"
          :step="1"
          :show-tooltip="false"
          class="w-20" />
        
        <span class="text-sm text-gray-600 ml-4 text-nowrap">颜色：</span>
        <input
          type="color"
          v-model="brushColor"
          class="w-[64px] h-[16px] border border-gray-300 rounded cursor-pointer" />
      </div>
      
      <!-- 画布区域 -->
      <div class="signature-canvas-container bg-white border-2 border-blue-300 rounded-lg relative shadow-inner">
        <canvas
          ref="canvasRef"
          @mousedown="startDrawing"
          @mousemove="draw"
          @mouseup="stopDrawing"
          @mouseleave="stopDrawing"
          @touchstart="startDrawing"
          @touchmove="draw"
          @touchend="stopDrawing"
          class="signature-canvas cursor-crosshair"
          width="450"
          height="200">
        </canvas>
        
        <!-- 提示文字 -->
        <div
          v-if="isEmpty"
          class="absolute inset-0 flex items-center justify-center pointer-events-none">
          <span class="text-gray-400 text-sm">请在此处签名</span>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="isEmpty">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import { ElDialog, ElButton, ElSlider, ElDivider, ElTooltip } from 'element-plus'
import { RefreshLeft, Delete } from '@element-plus/icons-vue'

// Props 和 Emits
const props = withDefaults(defineProps<{
  modelValue?: boolean
}>(), {
  modelValue: false
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: { value: string; width: number; height: number }): void
  (e: 'cancel'): void
}>()

// 响应式状态
const visible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => {
    emit('update:modelValue', val)
  }
})

// 画布相关
const canvasRef = ref<HTMLCanvasElement>()
const ctx = ref<CanvasRenderingContext2D>()
const isDrawing = ref(false)
const brushSize = ref(3)
const brushColor = ref('#000000')
const pathHistory = ref<ImageData[]>([])
const isEmpty = ref(true)

// 计算属性
const canUndo = computed(() => pathHistory.value.length > 0)

// 生命周期
onMounted(() => {
  initCanvas()
})

watch(visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initCanvas()
    })
  }
})

// 初始化画布
const initCanvas = () => {
  if (!canvasRef.value) return
  
  ctx.value = canvasRef.value.getContext('2d')!
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
  
  // 设置画布背景为白色
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height)
  
  saveState()
}

// 保存画布状态
const saveState = () => {
  if (!ctx.value || !canvasRef.value) return
  const imageData = ctx.value.getImageData(0, 0, canvasRef.value.width, canvasRef.value.height)
  pathHistory.value.push(imageData)
  
  // 限制历史记录数量
  if (pathHistory.value.length > 20) {
    pathHistory.value.shift()
  }
}

// 获取鼠标/触摸位置
const getEventPos = (e: MouseEvent | TouchEvent) => {
  const rect = canvasRef.value!.getBoundingClientRect()
  const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX
  const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY
  
  return {
    x: clientX - rect.left,
    y: clientY - rect.top
  }
}

// 开始绘画
const startDrawing = (e: MouseEvent | TouchEvent) => {
  e.preventDefault()
  isDrawing.value = true
  
  const pos = getEventPos(e)
  if (!ctx.value) return
  
  ctx.value.beginPath()
  ctx.value.moveTo(pos.x, pos.y)
  ctx.value.strokeStyle = brushColor.value
  ctx.value.lineWidth = brushSize.value
}

// 绘画中
const draw = (e: MouseEvent | TouchEvent) => {
  if (!isDrawing.value || !ctx.value) return
  e.preventDefault()
  
  const pos = getEventPos(e)
  ctx.value.lineTo(pos.x, pos.y)
  ctx.value.stroke()
  
  isEmpty.value = false
}

// 停止绘画
const stopDrawing = () => {
  if (!isDrawing.value) return
  isDrawing.value = false
  saveState()
}

// 撤销
const handleUndo = () => {
  if (pathHistory.value.length <= 1) return
  
  pathHistory.value.pop() // 移除当前状态
  const prevState = pathHistory.value[pathHistory.value.length - 1]
  
  if (prevState && ctx.value) {
    ctx.value.putImageData(prevState, 0, 0)
  }
  
  // 检查是否为空
  checkIsEmpty()
}

// 清空画布
const handleClear = () => {
  if (!ctx.value || !canvasRef.value) return
  
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height)
  
  pathHistory.value = []
  isEmpty.value = true
  saveState()
}

// 检查画布是否为空
const checkIsEmpty = () => {
  if (!ctx.value || !canvasRef.value) return
  
  const imageData = ctx.value.getImageData(0, 0, canvasRef.value.width, canvasRef.value.height)
  const data = imageData.data
  
  // 检查是否有非白色像素
  for (let i = 0; i < data.length; i += 4) {
    if (data[i] !== 255 || data[i + 1] !== 255 || data[i + 2] !== 255) {
      isEmpty.value = false
      return
    }
  }
  isEmpty.value = true
}

// 确定
const handleConfirm = () => {
  if (!canvasRef.value || isEmpty.value) return
  
  const dataURL = canvasRef.value.toDataURL('image/png')
  emit('confirm', {
    value: dataURL,
    width: canvasRef.value.width,
    height: canvasRef.value.height
  })
  
  handleClose()
}

// 取消/关闭
const handleClose = () => {
  emit('cancel')
  visible.value = false
  
  // 重置状态
  handleClear()
}
</script>

<style scoped>
.signature-dialog {
  user-select: none;
}

.signature-container {
  width: 100%;
}

.signature-toolbar {
  border: 1px solid #e5e7eb;
}

.signature-canvas-container {
  width: 100%;
  height: 200px;
  position: relative;
  overflow: hidden;
  background: #fefefe;
  border: 2px solid #60a5fa !important;
  box-shadow: inset 0 2px 4px rgba(96, 165, 250, 0.1);
}

.signature-canvas {
  display: block;
  width: 100%;
  height: 100%;
}

/* 禁用触摸滚动 */
.signature-canvas-container {
  touch-action: none;
}
</style> 